<?php
$arr = explode("?",$_SERVER['REQUEST_URI']);
$uri = $arr[0];

/**
 * 列出用户
 */
if($uri == "/api/admin/users"){
    $page = $_GET['page'];
    $size = $_GET['size'];
    $data = $cnSql->read("users",$page,$size,"1=1",$total);
    $outJson->data = $data;
    $outJson->code = 200;
    $outJson->total = $total;
    echo json_encode($outJson);
}


/**
 * 新增用户
 */
if($uri == "/api/admin/user/create"){
    $postJson = json_decode(file_get_contents("php://input"));
    $username = $postJson->username;
    $remark = $postJson->remark;
    // 验证用户名
    if(empty($username)) {
        $outJson->msg = "用户名不能为空";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 检查用户名长度 (3-20个字符)
    if(mb_strlen($username) < 3 || mb_strlen($username) > 20) {
        $outJson->msg = "用户名长度必须在3-20个字符之间";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 用户名只允许字母数字下划线
    if(!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $outJson->msg = "用户名只能包含字母、数字和下划线";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 防SQL注入
    $username = addslashes($username);

    // 防XSS注入
    if(!empty($remark)) {
        $remark = htmlspecialchars($remark, ENT_QUOTES, 'UTF-8');
    }
    $sql_id = $cnSql->insert_json("users",array('user'=>$username,'remark'=>$remark));
    if($sql_id){
        $outJson->msg = "添加成功";
        $outJson->code = 200;
    }else{
        $outJson->msg = "添加失败";
        $outJson->msg = 500;
    }
    echo json_encode($outJson);
}

/**
 * 登录后台
 */
if($uri == "/api/admin/login"){
    $postJson = json_decode(file_get_contents("php://input"));
    $username = $postJson->username;
    $password = $postJson->password;
    $sql = $cnSql->read_only("users","user = '$username' and password = '$password' and type = 1");
    if($sql){
        $outJson->msg = "登录成功";
        $outJson->code = 200;
        $_SESSION['admin_user'] = $sql;
    }else{
        $outJson->msg = "登录失败";
        $outJson->code = 500;
    }
    echo json_encode($outJson);
}

/**
 * 判断是否登录
 */
if($uri == "/api/admin/check-auth"){
    if(isset($_SESSION['admin_user'])){
        $outJson->msg = "已登录";
        $outJson->code = 200;
    }else{
        $outJson->msg = "未登录";
        $outJson->code = 500;
    }
    echo json_encode($outJson);
}
?>